package com.starry.chat.ui

import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.drake.brv.BindingAdapter
import com.drake.brv.utils.linear
import com.drake.brv.utils.setup
import com.starry.chat.R
import com.starry.chat.databinding.ActivityChatBinding
import com.starry.chat.databinding.ItemMsgLeftBinding
import com.starry.chat.databinding.ItemMsgRightBinding
import com.starry.chat.logic.model.ChatBodyBean
import com.starry.chat.viewmodel.ChatViewModel
import com.starry.core.base.BaseActivity
import com.starry.core.ext.singleClick
import com.starry.core.ext.toast
import com.starry.core.utils.ZKStatusBarUtil


@Route(path = "/chat/ui/ChatActivity")
class ChatActivity : BaseActivity<ActivityChatBinding, ChatViewModel>() {

    private val TAG = "ChatActivity"
    private val messageDtoList = mutableListOf<ChatBodyBean.MessagesDTO>()
    private lateinit var rvChat:RecyclerView
    private lateinit var chatAdapter: BindingAdapter
    @SuppressLint("NotifyDataSetChanged")
    override fun initData() {


        mDataBinding.tvSend.singleClick {
            val message = mDataBinding.edContent.text.toString()

            if(message.isEmpty()){
                toast("请输入问题！")
            }
            messageDtoList.add(ChatBodyBean.MessagesDTO("user", message))
            mDataBinding.edContent.setText("")
            chatAdapter.notifyDataSetChanged()
            mDataBinding.llPlaceholder.visibility = View.VISIBLE
            mDataBinding.ivPlaceholder.visibility = View.VISIBLE
            mDataBinding.tvPlaceholderMsgLeft.animation()
            mViewModel.getBaiduToken()
        }

        mViewModel.token.observeForever {
            if(it.isSuccess){
                val data = it.getOrNull()
                data?.let {chatToken ->
                    chatToken.accessToken?.let {accessToken ->
                        val chatBodyBean = ChatBodyBean()
                        chatBodyBean.messages = messageDtoList
                        chatBodyBean.system =
                            "你是一款智能中医大模型助手，中文名字叫做岐黄智语，问答场景下请以一名家庭医生的角色组织语言，帮助解决人们日常生活中可能出现的各种生活疾病"
                        mViewModel.startChat(chatBodyBean, accessToken)
                    }
                }
            }
        }

        mViewModel.chat.observeForever {
            if(it.isSuccess){
                val data = it.getOrNull()
                data?.let {chatBean ->
                    mDataBinding.llPlaceholder.visibility = View.GONE
                    mDataBinding.ivPlaceholder.visibility = View.GONE
                    mDataBinding.tvPlaceholderMsgLeft.stopAnimation()
                    chatBean.result?.let {result ->
                        messageDtoList.add(ChatBodyBean.MessagesDTO("assistant", ""))
                        chatAdapter.models = messageDtoList
                        rvChat.scrollToPosition(messageDtoList.size - 1)

                        val length = result.length
                        var index = 0
                        Thread {
                            while (index < length) {
                                try {
                                    Thread.sleep(20)
                                    runOnUiThread {
                                        messageDtoList[messageDtoList.size - 1].content =
                                            result.substring(0, index)
                                        //刷新列表
                                        chatAdapter.notifyDataSetChanged()
                                        chatAdapter.notifyItemInserted(messageDtoList.size - 1)
                                        rvChat.scrollToPosition(messageDtoList.size - 1)
                                        mDataBinding.edContent.setText("")
                                    }
                                    index++
                                } catch (e: Exception) {
                                    e.printStackTrace()
                                }
                            }
                        }.start()
                        chatAdapter.notifyDataSetChanged()
                    }
                }
            }
        }
    }

    override fun initView() {

        ZKStatusBarUtil.setTransparentForWindow(getContext())
        ZKStatusBarUtil.setDarkMode(getContext())
        mDataBinding.titleTopBar.baseTvTitle.text = "健康医生"
        mDataBinding.titleTopBar.baseIvBack.setOnClickListener {
            finish()
        }
        mDataBinding.titleTopBar.baseIvBack.visibility = View.VISIBLE

        rvChat = mDataBinding.rvView
        chatAdapter = rvChat.linear().setup {
            addType<ChatBodyBean.MessagesDTO>{
                when(role){
                    "user" -> {
                        R.layout.item_msg_right
                    }
                    else -> {
                        R.layout.item_msg_left
                    }
                }
            }
            onBind {
                val model=getModel<ChatBodyBean.MessagesDTO>()
                when(itemViewType){
                    R.layout.item_msg_right -> {
                        getBinding<ItemMsgRightBinding>().tvMsgRight.text = model.content
                    }
                    R.layout.item_msg_left -> {
                        getBinding<ItemMsgLeftBinding>().tvMsgLeft.text = model.content
                    }
                }
            }
        }
        chatAdapter.models = messageDtoList
    }

    override fun getLayoutId() = R.layout.activity_chat
}